package net.yxsoft.kit;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * Created by 刘飞 on 2017/5/6.
 */
public class OSSKit {

  private static String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
  private static String accessKeyId = "LTAI4gKxogAGox5R";
  private static String accessKeySecret = "KbG4VKO48FStTNj0tGltr1oJ4cp9Jy";
  private static String bucketName = "hechaba";
  private static String key = "<key>";
  // 设置URL过期时间为1天
  private static final Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 24);


  //在自己内部定义自己的一个 实例，只供内部调用
  private static final OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

  public static OSSClient getOSSClient() {
    return client;
  }

  // 上传文件 file
  public static void uploadImage(String key, File file) throws OSSException, ClientException, FileNotFoundException {
    // 获取指定文件的输入流
    InputStream content = new FileInputStream(file);
    // 创建上传Object的Metadata
    ObjectMetadata meta = new ObjectMetadata();
    // 必须设置ContentLength
    meta.setContentLength(file.length());
    meta.setContentType("image/*");
    client.putObject(bucketName, key, content, meta);

    System.out.println("上传图片 " + key + "成功");
  }


  //生成URL
  public static URL getUrl(String key) {

    URL url = client.generatePresignedUrl(bucketName, key, expiration);
    return url;
  }

  // 下载文件
  public static void downloadFile(OSSClient client, String bucketName, String key, String fileDownloadPath)
    throws OSSException, ClientException {
    client.getObject(new GetObjectRequest(bucketName, key), new File(fileDownloadPath));
  }

  public static void main(String[] args) {

    File file = new File("F:\\image\\avatar\\573402170.jpg");

    try {
      uploadImage("article/573402170.jpg", file);
      System.out.println("上传图片成功");
    } catch(FileNotFoundException e) {
      e.printStackTrace();
    }
  }
}
